package com.carkeeper.service.impl;
import com.alibaba.fastjson.JSON;
import com.carkeeper.entity.Result;
import com.carkeeper.entity.StatusCode;
import com.carkeeper.feign.KnowledgeFeign;
import com.carkeeper.mapper.BlogCategoryMapper;
import com.carkeeper.mapper.ComponentMapper;
import com.carkeeper.mapper.DiscoverMapper;
import com.carkeeper.pojo.Blog;
import com.carkeeper.pojo.BlogCategory;
import com.carkeeper.service.DiscoverService;
import com.carkeeper.util.IdWorker;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class DiscoverServiceImpl implements DiscoverService {

    @Autowired
    private DiscoverMapper discoverMapper;

    @Autowired
    private BlogCategoryMapper blogCategoryMapper;


    @Autowired
    private IdWorker idWorker;

    @Autowired
    private KnowledgeFeign knowledgeFeign;


    @Autowired
    private ComponentMapper componentMapper;


    @Override
    public PageInfo<Blog> multipartConditionFindBlog(Map<String, String> map, String currentPage, String pageSize) {

        currentPage = StringUtils.isNotBlank(currentPage) ? currentPage : "1";
        pageSize = StringUtils.isNotBlank(pageSize) ? pageSize : "10";

        //添加分页
        try {
            int current = Integer.parseInt(currentPage);
            int size = Integer.parseInt(pageSize);
            PageHelper.startPage(current, size);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("分页参数错误！");
        }


        //创建条件添加器
        Example example = new Example(Blog.class);
        //创建条件对象
        Example.Criteria criteria = example.createCriteria();
        if (map != null && map.size() >= 1) {
            //判断name查询条件
            String title = map.get("title");
            if (StringUtils.isNotBlank(title)) {
                criteria.andEqualTo("title", title);
            }
            //判断分类查询条件
            String categoryName = map.get("categoryName");
            if (StringUtils.isNotBlank(categoryName)) {
                //查询categoryId对应的category
                BlogCategory blogCategory = blogCategoryMapper.selectByPrimaryKey(categoryName);
                //判断查询结果
                if (StringUtils.isNotBlank(blogCategory.getId() + "")) {
                    //添加条件
                    criteria.andEqualTo("blogCategoryId", blogCategory.getId());
                }
            }

            //判断发布人查询条件
            String createName = map.get("createName");
            if (StringUtils.isNotBlank(createName)) {
                //根据发布人name查询发布人id
                //------------------------
                //判断是否为空
                if (StringUtils.isNotBlank("发布人对象是否为空")) {
                    //添加条件
                    criteria.andEqualTo("creator", "发布人id");
                }
            }

            //判断判断文稿状态查询条件
            String states = map.get("status");
            if (StringUtils.isNotBlank(states) && states.contains("1") && states.contains("0")) {
                criteria.andEqualTo("status", states);
            }

            //判断时间区查询条件
            String queryTime = map.get("queryTime");
            if (StringUtils.isNotBlank(queryTime)) {
                String startTime = null;
                String endTime = null;

                try {
                    //以逗号分隔
                    String[] timeInterval = queryTime.trim().split(",");
                    //2020-11-19 17:59:06
                    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date01 = simpleDateFormat2.parse(timeInterval[0]);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    startTime = simpleDateFormat.format(date01);

                    //开始时间
                    //2020-11-19 17:59:06
                    SimpleDateFormat simpleDateFormat01 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    SimpleDateFormat simpleDateFormat03 = new SimpleDateFormat("yyyy-MM-dd");
                    Date parse = simpleDateFormat01.parse(timeInterval[1]);
                    endTime = simpleDateFormat03.format(parse);
                    //结束时间
                } catch (ParseException e) {
                    e.printStackTrace();
                    throw new RuntimeException("时间解析异常！");
                }
                //添加条件
                criteria.andGreaterThanOrEqualTo("createTime", startTime).andLessThanOrEqualTo("createTime", endTime);
            }
        }

        try {
            //执行查询
            List<Blog> blogs = discoverMapper.selectByExample(example);
            //创建pageInfo

            return new PageInfo<Blog>(blogs);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查询执行异常！");
        }

    }

    /**
     * 查询全部分类
     *
     * @return
     */
    @Override
    public List<BlogCategory> findAllCategory() {
        return blogCategoryMapper.selectAll();
    }


    /**
     * 添加文稿
     *
     * @param map
     * @return
     */
    @Override
    public Result addBlog(Map<String, String> map) {
        try {
            //取出标题
            String name = map.get("name");
            //取出照片名称
            String cover = map.get("cover");
            //转换为字符串
            String s = JSON.toJSONString(map);
            //转换为对象
            Blog blog = JSON.parseObject(s, Blog.class);
            //设置id
            blog.setId(idWorker.nextId());
            //设置生成时间2020-11-23 13:03:50
            SimpleDateFormat createDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String createTime = createDateFormat1.format(new Date());
            blog.setCreateTime(createTime);
            //设置更新时间
            blog.setUpdateTime(createTime);
            //查询发布人信息
            //----------------------------------
            //执行保存
            int insert = discoverMapper.insert(blog);
            return new Result(true, StatusCode.OK, "添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("添加异常！");
        }
    }








    /**
     * 根据分类查询知识库
     *
     * @param type
     * @return
     */
   /* @Override
    public Result<Map<String, List>> findKnowledgeByCategory(String type) {
        Map<String, List> map = new HashMap();
        //封装配件类知识库
        List<Component> components = new ArrayList<>();
        //封装服务类知识库
        List<Component> service = new ArrayList<>();
        //查询查询分类对应的知识库
        Result<List<KnowledgeBaseInfo>> knowledgeByCategory = knowledgeFeign.findKnowledgeByCategory(type);
        //遍历知识库集合
        List<KnowledgeBaseInfo> data = knowledgeByCategory.getData();
        for (KnowledgeBaseInfo datum : data) {
            if (type.equals(datum.getType())) {
                //创建条件创建对象
                Example example = new Example(Component.class);
                Example.Criteria criteria = example.createCriteria();
                //添加条件
                criteria.andEqualTo("type1", datum.getType01Id()).andEqualTo("type2", datum.getType02Id());

                List<Component> components1 = componentMapper.selectByExample(example);
                //遍历知识库
                for (Component component : components1) {
                    components.add(component);
                }
            } else if ("服务".equals(datum.getType())) {
                //模拟查询服务相关文库后再以文库的类型查询
            }

        }
        map.put("component", components);
        map.put("service", service);

        return new Result<>(true, StatusCode.OK, "查询成功！", map);
    }*/


    /**
     * 根据id查询文稿详情
     *
     * @param id
     * @return
     */
    public Result<Blog> findBlogById(String id) {
        Blog blog = discoverMapper.selectByPrimaryKey(id);
        return new Result<>(true, StatusCode.OK, "查询文稿详情成功！", blog);
    }

    /**
     *
     * @param id
     * @return
     */
    @Override
    public Result update(String id) {

        return null;
    }

}

